package com.sunseaypw.springmvc.web;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
public class ChatHandler extends TextWebSocketHandler {
    // 保存所有Client的WebSocket会话实例:
    private Map<String, WebSocketSession> clients = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 新会话根据ID放入Map:
        clients.put(session.getId(), session);
        session.getAttributes().put("name", "Guest1");
        for(var key : session.getAttributes().keySet()){
            System.out.println(String.format("key:%s value:%s", key,session.getAttributes().get(key)));
        }
    }
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String s = message.getPayload();        
        System.out.println("收到："+s);   
        String json = "from clientid："+session.getId()+" msg:"+s;
        TextMessage tomessage = new TextMessage(json);
        for (String id : clients.keySet()) {
            if(session.getId()!=id){
                WebSocketSession tosession = clients.get(id);
                tosession.sendMessage(tomessage);
            }            
        }
    }
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        clients.remove(session.getId());
    }
}
